package com.mi.system.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mi.system.dto.query.DictQueryDTO;
import com.mi.system.dto.request.DictRequestDTO;
import com.mi.system.entity.Dict;
import com.mi.system.mapper.DictMapper;
import com.mi.system.vo.DictVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * Dict service
 *
 * @author jin_huaquan
 * @version 1.0
 * @date 2021/11/1 14:00
 */
@Service
@RequiredArgsConstructor
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    public Page<DictVO> listDict(Page page, DictQueryDTO query) {
        return baseMapper.selectByPage(page, query);
    }

    @Override
    @Transactional(rollbackFor = TransactionException.class)
    public boolean saveDict(DictRequestDTO request) {
        Assert.isFalse(existsByType(request.getType()), "已存在相同的字典类型");

        Dict dict = new Dict();

        BeanUtil.copyProperties(request, dict);

        return this.save(dict);
    }

    @Override
    @Transactional(rollbackFor = TransactionException.class)
    public boolean updateDict(Long id, DictRequestDTO request) {
        Dict dict = baseMapper.selectById(id);
        Assert.notNull(dict, "未找到对应的字典类型");

        if (!Objects.equals(dict.getType(), request.getType())) {
            Assert.isFalse(existsByType(request.getType()), "已存在相同的字典类型");
        }

        BeanUtil.copyProperties(request, dict);

        return this.updateById(dict);
    }

    @Override
    @Transactional(rollbackFor = TransactionException.class)
    public Dict removeDict(Long id) {
        Dict dict = baseMapper.selectById(id);
        Assert.notNull(dict, "未找到对应的字典类型");

        baseMapper.deleteById(dict);

        return dict;
    }

    private boolean existsByType(String type) {
        return baseMapper.selectCount(Wrappers.<Dict>lambdaQuery().eq(Dict::getType, type)) > 0;
    }
}
